#!/bin/bash
#
###############################################################################
#                                                                             #
#                     Pi-Star Firmware Downgrade Tool                         #
#                                                                             #
#    Version 0.2, Code, Design and Development by Florian Wolters (DF2ET).    #
#                     Idea by Stefan Espringal (DL1BH)                        #
#                                                                             #
#                  Based on work by Andy Taylor (MW0MZW)                      #
#                         and Andy Uribe CA6JAU                               #
#                                                                             #
#               Make it simple to downgrade the Firmware                      #
#                                                                             #
###############################################################################
#
if [ "$(id -u)" != "0" ]; then
  echo -e "You need to be root to run this command...\n"
  exit 1
fi
#

#
# Output some usefull information when no variables are passed
#
if [ -z "$1" ]
then
  echo "This tool is used to downgrade the firmware of your MMDVM_HS Hat Modem"
  echo "to use the command, you will need to pass the name of your modem,"
  echo "please choose form the list below..."
  echo ""
  echo "To downgrade HS_HAT (14.7456MHz TCXO) connected to GPIO, run: pistar-mmdvmhshatdowngrade hs_hat"
  echo "To downgrade HS_HAT (12.288MHz TCXO) connected to GPIO, run: pistar-mmdvmhshatdowngrade hs_hat-12mhz"
  echo "To downgrade HS_DUAL_HAT (14.7456MHz TCXO) connected to GPIO, run: pistar-mmdvmhshatdowngrade hs_dual_hat"
  echo "To downgrade HS_DUAL_HAT (12.2880MHz TCXO) connected to GPIO, run: pistar-mmdvmhshatdowngrade hs_dual_hat-12mhz"
  echo ""
  # Get the pretty name for the chosen Modem according to the dashboard.
  if [ -f '/etc/dstar-radio.mmdvmhost' ]; then
    # Get the modem that the user has selected.
    modemSelected=$(grep 'Hardware=' /etc/dstar-radio.mmdvmhost)
    modemSelected=${modemSelected#*=}

    # Get the user friendly version of the selected Modem.
    modemSelectedHuman=$(grep ${modemSelected} /var/www/dashboard/admin/configure.php)
    modemSelectedHuman=${modemSelectedHuman#*\">}
    modemSelectedHuman=${modemSelectedHuman::-9}
    echo "Selected Modem:     ${modemSelectedHuman}"
  fi

  # Get the Modem info from the Log
  numLogs=$(ls -1rt /var/log/pi-star/MMDVM-*.log | wc -l)
  if [[ ${numLogs} -gt 0 ]]; then
    # Get the physically connected modem from the logs
    modemLog=$(tac $(ls -1rt /var/log/pi-star/MMDVM-*.log | tail -n1 ) | grep "protocol" -m 1 | sed -n 's/description: /&\n/;s/.*\n//p')
    echo "Connected Hardware: ${modemLog}"
    
    # Get the TCXO data
    if [[ ${modemLog} == *"MHz"* ]]; then
      tcxoData=$(echo ${modemLog} | awk '{print $3}')
      echo "TCXO Value:         ${tcxoData}"
    fi
  fi
  exit 0
fi
#
# OK we know what the modem is, let get the firmware string from the log...
#
tac $(ls -1rt /var/log/pi-star/MMDVM-*.log | tail -n1 ) | grep "protocol" -m 1 | sed -n 's/description: /&\n/;s/.*\n//p'
read -n 1 -s -r -p "Press any key to downgrade the ${1} firmware on this modem or Ctrl-C to quit..."
echo ""

# Get all releases and let the user choose or check if seconad command line option is a valid version tag
#

mapfile -t VERSIONS < <( curl -s -L https://api.github.com/repos/juribeparada/MMDVM_HS/releases | grep "tag_name" | sed -e 's/.*\(v[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\).*/\1/' )

VERSION=""
if [ "$2" ]
then
   echo -n "Checking your choice \"$2\" against release tags..."
   if [[ ! " ${VERSIONS[@]} " =~ " $2 " ]]
   then
      echo "not found!"
   else
      echo "found."
      VERSION="$2"
   fi
   echo ""
fi

if [ -z "$2" ] || [ $VERSION == "" ]
then
   echo "Please choose the version to flash from the following list of ${#VERSIONS[@]} items by entering the corresponding line number:"
   I=1
   for ITEM in "${VERSIONS[@]}"
   do
      echo "${I}) ${ITEM}"
      I=$((I + 1))
   done
   echo ""
   echo -n "Please enter your choice or \"q\" to abort and press [ENTER]: "
   read CHOICE
   echo ""
   if [ "$CHOICE" == "q" -o "$CHOICE" == "Q" ]; then
      echo "Aborted."
      exit 1
   elif [ $CHOICE -ge 1 -a $CHOICE -le ${#VERSIONS[@]} ]; then
      echo "Your choice: ${CHOICE} (${VERSIONS[(($CHOICE - 1))]})"
      echo ""
      VERSION="${VERSIONS[(($CHOICE - 1))]}"
      #
      # Download the correct firmware
      #
      case ${1} in
         hs_hat)
            # Flashing MMDVM_HS Hat Modem
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            mkdir /tmp/mmdvmhshatfirmware 2> /dev/null
            echo "Flashing your ${1} modem to version ${VERSION}"
            wget https://github.com/juribeparada/MMDVM_HS/releases/download/${VERSION}/install_fw_hshat.sh -O /tmp/mmdvmhshatfirmware/flash.sh
            chmod +x /tmp/mmdvmhshatfirmware/flash.sh
            cd  /tmp/mmdvmhshatfirmware
            ./flash.sh
            echo ""
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            read -n 1 -s -r -p "Flashing your ${1} modem complete, press any key to reboot your Pi-Star System..."
            shutdown -r now
            exit 0
         ;;
         hs_hat-12mhz)
            # Flashing MMDVM_HS Hat Modem with 12.288 MHz TCXO
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            mkdir /tmp/mmdvmhshatfirmware 2> /dev/null
            echo "Flashing your ${1} modem to the ${VERSION} version"
            wget https://github.com/juribeparada/MMDVM_HS/releases/download/${VERSION}/install_fw_hshat-12mhz.sh -O /tmp/mmdvmhshatfirmware/flash.sh
            chmod +x /tmp/mmdvmhshatfirmware/flash.sh
            cd  /tmp/mmdvmhshatfirmware
            ./flash.sh
            echo ""
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            read -n 1 -s -r -p "Flashing your ${1} modem complete, press any key to reboot your Pi-Star System..."
            shutdown -r now
            exit 0
         ;;
         hs_dual_hat)
            # Flashing MMDVM_HS_DUAL Modem
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            mkdir /tmp/mmdvmhshatfirmware 2> /dev/null
            echo "Flashing your ${1} modem to the ${VERSION} version"
            wget https://github.com/juribeparada/MMDVM_HS/releases/download/${VERSION}/install_fw_hsdualhat.sh -O /tmp/mmdvmhshatfirmware/flash.sh
            chmod +x /tmp/mmdvmhshatfirmware/flash.sh
            cd  /tmp/mmdvmhshatfirmware
            ./flash.sh
            echo ""
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            read -n 1 -s -r -p "Flashing your ${1} modem complete, press any key to reboot your Pi-Star System..."
            shutdown -r now
            exit 0
         ;;
         hs_dual_hat-12mhz)
            # Flashing MMDVM_HS_DUAL Modem with 12.288 MHz TCXO
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            mkdir /tmp/mmdvmhshatfirmware 2> /dev/null
            echo "Flashing your ${1} modem to the ${VERSION} version"
            wget https://github.com/juribeparada/MMDVM_HS/releases/download/${VERSION}/install_fw_hsdualhat-12mhz.sh -O /tmp/mmdvmhshatfirmware/flash.sh
            chmod +x /tmp/mmdvmhshatfirmware/flash.sh
            cd  /tmp/mmdvmhshatfirmware
            ./flash.sh
            echo ""
            rm -rf /tmp/mmdvmhshatfirmware 2> /dev/null
            read -n 1 -s -r -p "Flashing your ${1} modem complete, press any key to reboot your Pi-Star System..."
            shutdown -r now
            exit 0
         ;;
         *)
            # Un-recognised modem choice
            echo "Your Choice of ${1} modem is not supported by this update tool"
            exit 1
         ;;
      esac
   else
      echo "Invalid choice. Aborting ..."
      exit 2
   fi

fi
exit 2
